#import "THTipInputView.h"
#import "HWTFCursorView.h"
@interface THTipInputView () <UITextViewDelegate>
{
    CGFloat keyBoardHeight;
}
@property (nonatomic,strong) UIVisualEffectView *backgroundView;
@property (nonatomic,strong) UIView *shadowView;
@property (nonatomic,strong) UIView *keyBoardView;
@property (nonatomic,strong) UILabel *titleLabel;
@property (nonatomic,strong) UIButton *closeButton;
@property (nonatomic ,strong) UIImageView *verifyImageV;
@property (nonatomic, strong) UILabel *tipLabel;
@property (strong,nonatomic) HWTFCursorView *msgCodeView;
@property (nonatomic ,copy) NSString * captcheId;
@end
@implementation THTipInputView
- (instancetype)initWithComplete:(void(^)(NSString * codeValue, NSString * captcheId))complete
{
    if (self = [super init]) {
        self.inputTextEndBlock = complete;
        [self setupSubViews];
        [self generatePic];
        [self obserRAC];
    }
    return self;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
}
- (void)generatePic {
    [self showLoading];
    [CTBaseRequest postRequestWithMethodName:CTPath(@"/canvasCreate", CTPathTypePost, nil) parametersDic:nil success:^(CTBaseRequest * _Nonnull operation, BOOL isSuccess, id  _Nonnull responseObject) {
        if (!isSuccess) {
            [self showInfoText:(NSString *)responseObject];
        } else {
            if (responseObject[@"matterContent"] != nil) {
                NSDictionary *dic = responseObject[@"matterContent"];
                NSString * captcheId = dic[@"captcheId"];
                self.captcheId = captcheId;
                [self.verifyImageV sd_setImageWithURL:[NSURL fullUrlForImg:captcheId] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                    [self dismissLoading];
                    self.verifyImageV.image = image;
                }];
            }
        }
    }];
}
- (void)setupSubViews
{
    self.frame = [UIScreen mainScreen].bounds;
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    self.backgroundView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    self.backgroundView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.backgroundView.frame = self.bounds;
    [self addSubview:self.backgroundView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
    [self.backgroundView addGestureRecognizer:tap];
    self.shadowView.frame = CGRectMake(0, screenSize.height - 254, screenSize.width, 254);
    [self addSubview:self.shadowView];
    self.keyBoardView = [UIView new];
    self.keyBoardView.backgroundColor = [UIColor whiteColor];
    self.keyBoardView.frame = self.shadowView.bounds;
    [self.shadowView addSubview:self.keyBoardView];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.keyBoardView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(13,13)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.keyBoardView.bounds;
    maskLayer.path = maskPath.CGPath;
    self.keyBoardView.layer.mask = maskLayer;
    [self.keyBoardView addSubview:self.titleLabel];
    [self.keyBoardView addSubview:self.closeButton];
    [self.keyBoardView addSubview:self.verifyImageV];
    [self.keyBoardView addSubview:self.tipLabel];
    [self.keyBoardView addSubview:self.msgCodeView];
    [self.closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(40);
        make.top.mas_equalTo(6.5);
        make.right.mas_equalTo(-6.5);
    }];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.keyBoardView);
        make.centerY.mas_equalTo(self.closeButton);
    }];
    [self.verifyImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(Ratio(143), Ratio(52)));
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(Ratio(30));
        make.centerX.mas_equalTo(self.keyBoardView);
    }];
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.verifyImageV.mas_bottom).offset(Ratio(8));
        make.left.right.mas_equalTo(self.keyBoardView);
    }];
    [self.msgCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tipLabel.mas_bottom).offset(Ratio(20));
        make.left.mas_equalTo(Ratio(86));
        make.right.mas_equalTo(Ratio(-86));
        make.height.mas_equalTo(50);
    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden:) name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark - Getter
- (UIView *)shadowView
{
    if(!_shadowView) {
        _shadowView = [[UIView alloc] init];
        _shadowView.layer.masksToBounds = NO;
        _shadowView.layer.shadowOffset = CGSizeMake(0, 0);
        _shadowView.layer.shadowRadius = 23;
        _shadowView.layer.shadowOpacity = 1;
        _shadowView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.1].CGColor;
    }
    return _shadowView;
}
- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.font = [UIFont systemFontOfSize:18.f weight:UIFontWeightMedium];
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.text = @"Enter the graphic verification code";
    }
    return _titleLabel;
}
- (UIButton *)closeButton
{
    if (!_closeButton) {
        _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeButton addTarget:self action:@selector(closeAction:) forControlEvents:UIControlEventTouchUpInside];
        [_closeButton setImage:[UIImage imageNamed:@"common_close"] forState:UIControlStateNormal];
    }
    return _closeButton;
}
- (UIImageView *)verifyImageV {
    if (!_verifyImageV) {
        _verifyImageV = [[UIImageView alloc] init];
        _verifyImageV.image = [UIImage imageNamed:@"home_numCollect"];
        _verifyImageV.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(generatePic)];
        [_verifyImageV addGestureRecognizer:tap];
    }
    return _verifyImageV;
}
#pragma mark - Set
- (void)setTitle:(NSString *)title
{
    _title = title;
    _titleLabel.text = title;
}
#pragma mark - Anim
- (void)show
{
    UIWindow *rootWindow = [UIApplication sharedApplication].keyWindow;
    [rootWindow addSubview:self];
    [self.msgCodeView becomeFirstResponder];
    self.backgroundView.alpha = 0;
    [UIView animateWithDuration:0.25 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
        self.backgroundView.alpha = 1;
    } completion:^(BOOL finished) {
    }];
}
- (void)dismiss
{
    [self endEditing:YES];
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
- (void)closeAction:(id)sender
{
    [self dismiss];
}
#pragma mark - UIKeyboard
- (void)keyboardDidShow:(NSNotification *)notification{
    CGRect keyBoardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat deltaY = keyBoardRect.size.height;
    keyBoardHeight = deltaY;
    [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        self.shadowView.transform = CGAffineTransformMakeTranslation(0, -deltaY);
    }];
}
- (void)keyboardDidHidden:(NSNotification *)notification{
    [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        self.shadowView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
    }];
}
#pragma mark - lazyLoading
- (UIVisualEffectView *)backgroundView {
    if (!_backgroundView) {
        UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        _backgroundView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
        _backgroundView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _backgroundView.frame = self.bounds;
        _backgroundView.userInteractionEnabled = YES;
    }
    return _backgroundView;
}
- (UILabel *)tipLabel {
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc] init];
        _tipLabel.numberOfLines = 1;
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        _tipLabel.textColor = [UIColor color77777D];
        _tipLabel.font = kFontSize(13);
        _tipLabel.text = @"Click on the picture to refresh";
    }
    return _tipLabel;
}
- (HWTFCursorView *)msgCodeView
{
    if (_msgCodeView == nil) {
        _msgCodeView = [[HWTFCursorView alloc] initWithCount:4 margin:0 borderColor:[UIColor colorA4A5AC]];
        _msgCodeView.textField.keyboardType = UIKeyboardTypeNamePhonePad;
    }
    return _msgCodeView;
}
#pragma mark - ARC
- (void)obserRAC{
    @weakify(self);
    [RACObserve(self.msgCodeView, code) subscribeNext:^(id x) {
        @strongify(self);
        if (self.msgCodeView.code.length == 4) {
            if (self.inputTextEndBlock) {
                self.inputTextEndBlock(self.msgCodeView.code, self.captcheId);
                [self dismiss];
            }
        }
    }];
}
@end
